package com.sun.showcase.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.sun.showcase.interceptor.AuthorizationInterceptor;
import com.sun.showcase.interceptor.LimitRateInterceptor;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer{
    @Autowired
    private AuthorizationInterceptor authorizationInterceptor;
    @Autowired
    private LimitRateInterceptor limitRateInterceptor;
	@Override 
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(authorizationInterceptor).addPathPatterns("/**");
		registry.addInterceptor(limitRateInterceptor).addPathPatterns("/**");
	}
    /**
     * 添加静态资源文件，外部可以直接访问地址
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //需要告知系统，这是要被当成静态文件的！
        //第一个方法设置访问路径前缀，第二个方法设置资源路径
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        WebMvcConfigurer.super.addResourceHandlers(registry);
    }

    /**
     * 1、 extends WebMvcConfigurationSupport
     * 2、重写下面方法;
     * setUseSuffixPatternMatch : 设置是否是后缀模式匹配，如“/user”是否匹配/user.*，默认真即匹配；
     * setUseTrailingSlashMatch : 设置是否自动后缀路径模式匹配，如“/user”是否匹配“/user/”，默认真即匹配；
     */
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
      configurer.setUseSuffixPatternMatch(false)
            .setUseTrailingSlashMatch(false);
    }
	/**
	 * 国际化
	 * @return
	 */
	@Bean(name="messageSource")
	public ResourceBundleMessageSource messageSource(){
		
		ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
		
		/**
		 * 取jdk local与basenames内的集合匹配 
		 */
		messageSource.setBasenames("i18n.messages_zh_CN");
		
		return messageSource;
	}
	// 指定加密器
	@Bean
	public PasswordEncoder passwordEncoder() {
		return PasswordEncoderFactories.createDelegatingPasswordEncoder();
	}
	@Bean
	UserDetailsService userDetailsService(){
        return new PhoneUserDetailsServiceImpl();
    }
}
